﻿using System.Diagnostics;
using System.Diagnostics.Contracts;

namespace System
{
    public static class TimeSpanExtentions
    {
        [DebuggerStepThrough, Pure]
        public static string ToShortString(this TimeSpan time)
        {
            var result = "";
            var empty = true;
            var days = time.Days;
            if(days != 0)
            {
                result = string.Format("{0}d", days);
                empty = false;
            }

            var hours = time.Hours;
            if(empty)
            {
                if(hours != 0)
                {
                    result = hours.ToString();
                    empty = false;
                }
            }
            else
                result += string.Format("{0:00}", hours);

            var minutes = time.Minutes;
            if(empty)
            {
                if(minutes != 0)
                {
                    result = minutes.ToString();
                    empty = false;
                }
            }
            else
                result += string.Format(":{0:00}", minutes);

            var seconds = time.Seconds;
            var miliseconds = time.Milliseconds;

            return empty
                    ? (seconds == 0 && miliseconds == 0
                        ? "0"
                        : (seconds + (double)miliseconds / 1000).ToString())
                    : string.Format((seconds >= 10 ? "{0}:{1}" : "{0}:0{1}"), result, seconds + (double)miliseconds / 1000);
        }
    }
}
